package eventx

import "sync"

// 默认的事件管理器
var defaultManager = NewManager(nil)

func GetEvent(event string) *Dispatcher {
	return defaultManager.GetDispatcher(event)
}

func NewManager(host interface{}) (obj *Manager) {
	obj = &Manager{
		dispatchers: map[string]*Dispatcher{},
		host:        host,
	}
	return
}

type Manager struct {
	dispatchers map[string]*Dispatcher
	host        interface{}
	sync.RWMutex
}

func (mgr *Manager) GetDispatcher(event string) *Dispatcher {
	mgr.RLock()
	d, ok := mgr.dispatchers[event]
	mgr.RUnlock()
	if !ok {
		d = newDispatcher(event)
		d.host = mgr.host
		mgr.Lock()
		mgr.dispatchers[event] = d
		mgr.Unlock()
	}
	return d
}

func (mgr *Manager) Dispose() {
	if mgr == nil {
		return
	}
	for _, val := range mgr.dispatchers {
		val.OffAll()
	}
}
